var moment = require('../utils/moment');
var pageSize = 20;

Page({
    data: {
        pageIndex: 0,
        todos: [],
        loadingTip: '上拉加载更多',
    },
    naviDetail: function () {
        wx.navigateTo({
            url: '../detail/detail'
        });
    },
    onShow: function () {
        this.loadData();
    },
    loadData: function () {
        wx.request({
            method: 'POST',
            url: 'http://node.it577.net:5001/list',
            data: {
                pageIndex: this.data.pageIndex
            },
            success: result => {
                setTimeout(() => {
                    wx.stopPullDownRefresh();
                }, 500);
                var todos = result.data.map(item => {
                    item.createdAt = moment(item.createdAt).format('YYYY-MM-DD');
                    return item;
                });
                this.setData({
                    todos: this.data.todos.concat(todos)
                })
                if (todos.length < pageSize) {
                    this.setData({
                        loadingTip: '没有更多内容'
                    });
                }
            }
        });
    },
    edit: function (e) {
        console.log(e)
        var index = e.currentTarget.dataset.index;
        var _id = this.data.todos[index]._id;
        wx.navigateTo({
            url: '../detail/detail?_id=' + _id
        });
    },
    finish: function (e) {
        var index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '确定要删除吗？',
            success: res => {
                if (res.confirm) {
                    wx.request({
                        method: 'POST',
                        url: 'http://node.it577.net:5001/delete',
                        data: {
                            _id: this.data.todos[index]._id
                        },
                        success: result => {
                            wx.showToast({
                                title: result.data.msg
                            });
                            this.loadData();
                        }
                    });
                }
            }
        });
    },
    onPullDownRefresh: function () {
        // 下拉刷新
        this.setData({
            pageIndex: 0,
            todos: []
        });
        this.loadData();
    },
    onReachBottom: function () {
        var pageIndex = this.data.pageIndex;
        this.setData({
            pageIndex: ++pageIndex
        });
        console.log('load');
        this.loadData();
    },
});